#include "Animation.h"

Animation::Animation(const char* filename, int noFrames, int frameTime, ColourKey key)// : Image(filename,r,g,b)
{
    this->noFrames = noFrames;
    this->frameTime = frameTime;

    // Load image into an SDL surface
    #if BUZZ_USE_SDL_IMAGE == 1
        SDL_Surface* surface = IMG_Load(filename);
    #else
        SDL_Surface* surface = SDL_LoadBMP(filename);
    #endif

	if(surface == NULL)
	{
		printf("Error: Could not load animation %s\n", filename);
		return;	
	}

	frames = new Image*[noFrames];

    SDL_Rect rec;
    rec.w = surface->w;
    rec.h = surface->h / noFrames;
    rec.x = 0;

    for(int i=0; i<noFrames; i++)
    {
        rec.y = i * rec.h;
        frames[i] = new Image(surface, &rec, key);
    }

    imageHeight = surface->h;

    height = imageHeight / noFrames;
	width = surface->w;

    // Loop by default
    looping = true;
    // Start the animation
    start();

    SDL_FreeSurface(surface);
}

Animation::~Animation()
{
    for(int i=0; i<noFrames; i++)
    {
        delete frames[i];
    }

    delete[] frames;
}

void Animation::start()
{
    startTime = SDL_GetTicks();
}

int Animation::getFrameNumber()
{
    // Time difference between start time and now;
    Uint32 difference = SDL_GetTicks() - startTime;

	int framesDifference = frameTime==0 ? 0 : difference / frameTime;

    // If reached the end of the loop, return last frame
    if(!looping && framesDifference >= noFrames-1) return noFrames-1;
    return framesDifference % noFrames;
}

Image* Animation::getCurrentFrame()
{
    return frames[getFrameNumber()];
}

void Animation::draw(int x, int y, bool flipped)
{
    /*int frameNumber = getFrameNumber();

    float refFrameHeight = (float) height / (float) actualHeight;

    // update texture reference coordinates to draw from the right part of the image
    texRefTop = frameNumber * refFrameHeight;
    texRefBottom = (float)(frameNumber+1) * refFrameHeight;

    Image::draw(x,y,flipped);*/

    getCurrentFrame()->draw(x,y,flipped);
}

int Animation::getPlayCount()
{
    // Time difference between start time and now;
    Uint32 difference = SDL_GetTicks() - startTime;

    int framesDifference = difference / frameTime;

    if(!looping) return framesDifference > noFrames-1 ? 1 : 0;

    return framesDifference / noFrames;

}

void Animation::setReferencePoint(int x, int y)
{
	Image::setReferencePoint(x,y);

	for(int i=0; i<noFrames; i++){
		frames[i]->setReferencePoint(x,y);
	}
}
